package org.xm.sk.controller.dbase;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
import org.springframework.data.domain.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.xm.sk.exception.DataNotFoundException;
import org.xm.sk.exception.RequestParamterException;
import org.xm.sk.service.data.BaseService;
import org.xm.sk.vo.ob.Ids;
import org.xm.sk.vo.ob.MapList;
import org.xm.sk.vo.ob.PageConf;
import org.xm.sk.vo.ob.ResultMsg;
import org.xm.sk.vo.tb.Image;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import springfox.documentation.annotations.ApiIgnore;

@SuppressWarnings("unchecked")
@Slf4j
@Api(tags = { "image" })
@RestController
@RequestMapping(value="/images")
public class ImageController {

    @Value("${app.upload.max-zip-size}")
    private String maxZipSize = "400KB";
    @Autowired
    private MessageSource messages;
    @Autowired
    private BaseService<Image> imageService;
    
    @ApiOperation(value="创建图片", notes="根据image对象创建图片，使用此接口需要ADMIN权限")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "file", value = "图片文件", required = true, dataType = "File", paramType = "form")
    })
    @PreAuthorize("hasRole('ADMIN')")
    @RequestMapping(value="", method=RequestMethod.POST)
    public Image add(@RequestPart MultipartFile file)
            throws IOException, RequestParamterException {
        double maxSize = 400 * 1024;
        if (maxZipSize.endsWith("MB")) {
            maxSize = Integer.parseInt(maxZipSize.substring(0, maxZipSize.lastIndexOf("MB"))) * 1024 * 1024;
        } else if (maxZipSize.endsWith("KB")) {
            maxSize = Integer.parseInt(maxZipSize.substring(0, maxZipSize.lastIndexOf("KB"))) * 1024;
        }
        Image image = new Image();
        image.setName(file.getOriginalFilename());
        if (maxSize < file.getBytes().length) {
            double per = maxSize / ((double) file.getBytes().length);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            Thumbnails.of(file.getInputStream()).scale(1f).outputQuality(per)
                    .toOutputStream(out);
            image.setFile(out.toByteArray());
            out.close();
        } else
            image.setFile(file.getBytes());
        return imageService.add(image);
    }

    @ApiIgnore()
    @ApiOperation(value="删除图片", notes="根据URI的id来指定删除对象")
    @ApiImplicitParam(name = "id", value = "图片ID", required = true, paramType = "path", dataType = "int")
    @RequestMapping(value="/{id}", method=RequestMethod.DELETE)
    public ResultMsg delete(@PathVariable Integer id) {
        imageService.delete(id);
        return new ResultMsg("200", messages.getMessage("success", null, "SUCCESS", null), new Date());
    }
    
    @ApiOperation(value="删除图片", notes="根据POST的id列表来指定删除对象，可批量")
    @ApiImplicitParam(name = "ids", value = "图片ID集", required = true, dataType = "Ids")
    @RequestMapping(value="/delete", method=RequestMethod.DELETE)
    public ResultMsg Batchdelete(@RequestBody Ids ids) {
        imageService.delete(ids.getIds());
        return new ResultMsg("200", messages.getMessage("success", null, "SUCCESS", null), new Date());
    }
    
    @ApiOperation(value="更新图片详细信息", notes="根据URI的id来指定更新对象，并根据传过来的image信息来更新图片详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "图片ID", required = true, paramType = "path", dataType = "int"),
            @ApiImplicitParam(name = "file", value = "图片文件", required = true, dataType = "File", paramType = "form")
    })
    @RequestMapping(value="/{id}", method=RequestMethod.PUT)
    public ResultMsg update(@PathVariable Integer id, @RequestPart MultipartFile file) throws DataNotFoundException, IOException {
        if (!file.isEmpty()) {
            Image u = (Image) imageService.findById(id);
            if (null == u) {
                throw new DataNotFoundException(Image.class.getName());
            }
            u.setName(file.getName());
            u.setFile(file.getBytes());
            imageService.update(u);
            return new ResultMsg("200", messages.getMessage("success", null, "SUCCESS", null), new Date());
        } else {  
            throw new IOException("file is empty!");
        }
    }

    @ApiOperation(value="获取图片详细信息", notes="根据URI的id来获取图片详细信息")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "header", dataType = "String", name = "authorization", defaultValue = "Bearer token", value = "令牌", required = false),
        @ApiImplicitParam(name = "id", value = "图片ID", required = true, paramType = "path", dataType = "int")
    })
    @RequestMapping(value="/{id}", method=RequestMethod.GET)
    public Image load(@PathVariable Integer id) throws DataNotFoundException {
        Image u = (Image) imageService.findById(id);
        if (null == u) {
            throw new DataNotFoundException(Image.class.getName());
        }
        return u;
    }
    
    @ApiOperation(value="获取图片文件", notes="根据URI的id来获取图片文件")
    @ApiImplicitParam(name = "id", value = "图片ID", required = true, paramType = "path", dataType = "int")
    @RequestMapping(value="/f/{id}", method=RequestMethod.GET)
    public void load4File(@PathVariable Integer id,
            HttpServletResponse response)
            throws DataNotFoundException, IOException {
        long st = System.currentTimeMillis();
        log.info("获取图片文件 START: {}", st);
        Image u = (Image) imageService.findById(id);
        long et = System.currentTimeMillis();
        log.info("获取图片文件 END0: {}, allcost: {}", et, et - st);
        if (null == u) {
            throw new DataNotFoundException(Image.class.getName());
        }
        byte[] contents = u.getFile();
        InputStream is = new ByteArrayInputStream(contents);
        response.setContentType("image/jpeg");
        ServletOutputStream out = response.getOutputStream();
        int len = 0;
        byte[] buf = new byte[1024 * 1024 *6];
        while ((len = is.read(buf, 0, 1024)) != -1) {
            out.write(buf, 0, len);
        }
        out.flush();
        out.close();
        et = System.currentTimeMillis();
        log.info("获取图片文件 END1: {}, allcost: {}", et, et - st);
    }
    
    @ApiOperation(value="获取图片列表", notes="根据提交的分页信息列出所以图片信息")
    @ApiImplicitParam(name = "pageConf", value = "分页信息实体", required = true, dataType = "PageConf")
    @RequestMapping(value={"/list"}, method=RequestMethod.POST)
    public MapList<Image> list(@RequestBody PageConf pageConf) {
        List<Image> u = null;
        Long allCount = null;
        Object o = imageService.findAllByPage(pageConf);
        if (o instanceof Page) {
            allCount = ((Page<Image>) o).getTotalElements();
            u = ((Page<Image>) o).getContent();
        } else {
            allCount = (long) ((List<Image>) o).size();
            u = (List<Image>) o;
        }
        return new MapList<Image>(allCount, u);
    }

    // --------------------- 业务具体接口 ---------------------
}
